const app = getApp()
import {
  decryptData,
  encryptionData
} from '../../../../../utils/public'
import {
  parseTime
} from '../../../../../utils/util'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: "001", // 001 设备归还
    order_log: [{
        title: '项目配置',
        created_at: '2020-12-18 16:23:56',
        content: '孙医生'
      },
      {
        title: '更换设备',
        created_at: '2020-12-18 16:23:56',
        content: '孙医生'
      }
    ],
    presentStageArr: [
      '待处理',
      '进行中',
      '已完成',
      '已逾期'
    ],
    presentStageSubArr: [
      '此订单还未绑定设备。',
      '订单正在进行中。',
      '该订单已完成。',
      '该订单已逾期，请联系购买者尽快返还设备。'
    ],
    orderNo: null,
    orderId: null,
    orderData: null,
    //蓝牙参数
    BTLTEST: '',
    btnFis: false,
    types: 1,
    deviceId: '',
    UUID1: '', //服务
    UUID2: '', //特征
    serviceId: '',
    characteristicId: '',
    commandEnd: 'AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF', //最终指令删除
    commandStart: 'AA13B9FFFFFFFFFFFFFFFFFFFFFFFFFF', //最终指令记录查询
    sumTimeDays: '', //总时长 
    sumTimeArray: [], //分时长
    successAB: '',
    isTwoReturn: false,
    modelid: wx.getStorageSync('modelid')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    wx.removeStorageSync('timeiS')
    this.setData({
      // orderId: decodeURIComponent(options.codeId),
      type: options.type
    })
    this.getSlist()
  },
  // onUnload() {
  //   wx.closeBluetoothAdapter()
  // },
  getSlist() {
    let that = this
    let locationEnabled = false
    let locationAuthorized = false
    let bluetoothEnabled = false
    // wx.closeBluetoothAdapter()
    wx.scanCode({
      onlyFromCamera: true,
      success: (resCode) => {
        console.log(resCode);
        if (resCode.errMsg == "scanCode:ok") {
          console.log(resCode, '扫码内容');
          if (!resCode.result.match(RegExp(/便携式低频脉冲治疗仪/))) {
            that.showDialog({
              title: '无效二维码',
              icon: 'fail',
              tip: ['请扫描设备背部二维码']
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 2000)
            return
          }
          let A = resCode.result.indexOf(';')
          let B = resCode.result.indexOf(';', A + 1)
          let deviceNo = resCode.result.substring(A + 1, B)
          let newYCL = resCode.result.slice(0, resCode.result.indexOf(';'))
          wx.setStorageSync('chb_key', that.addObjret(newYCL));
          that.setData({
            btnFis: false,
            BTLTEST: that.addObjret(newYCL),
            deviceNo: deviceNo,
          })
          wx.request({
            url: app.globalData.serverUrl + '/device/return/check/' + deviceNo,
            method: 'GET',
            header: {
              'token': wx.getStorageSync('token')
            },
            success: (resdeviceNo => {
              if (resdeviceNo.data.code == 200) {
                if (that.data.type == 'equipmentReturn') {
                  wx.showLoading({
                    title: '查询中...',
                    mask: true
                  })
                  wx.request({
                    url: app.globalData.serverUrl + '/ddOrder/detail/by/' + that.data.deviceNo,
                    method: 'GET',
                    header: {
                      'token': wx.getStorageSync('token')
                    },
                    success: (ressno => {
                      let resDatasno = ressno.data
                      if (resDatasno.code == 200) {
                        resDatasno.data.order.configurationTime = parseTime(resDatasno.data.order.configurationTime, '{y}-{m}-{d} {h}:{i}:{s}')
                        that.setData({
                          orderData: resDatasno.data.order
                        })
                        wx.hideLoading()
                        wx.showLoading({
                          title: '归还中...',
                          mask: true
                        })
                        wx.request({
                          url: app.globalData.serverUrl + '/device/compulsory/return',
                          method: 'POST',
                          header: {
                            'token': wx.getStorageSync('token')
                          },
                          data: {
                            orderId: resDatasno.data.order.orderId
                          },
                          success: (resEnd => {
                            wx.hideLoading()
                            if (resEnd.data.code == 200) {
                              that.showDialog({
                                title: '归还成功!',
                                icon: 'success',
                                tip: ['该订单已结束']
                              })
                              setTimeout(() => {
                                wx.reLaunch({
                                  url: '/pages/workbench/workbench',
                                })
                              }, 2000)

                            }
                          })
                        })

                      } else {
                        wx.hideLoading()
                        if (resDatasno.message.indexOf(',')) {
                          let arr = resDatasno.message.split(',')
                          let arr1 = []
                          arr.map((item, index) => {
                            if (index != 0) {
                              arr1.push(item)
                            }
                          })
                          that.showDialog({
                            title: arr[0],
                            icon: 'fail',
                            tip: [arr1]
                          })
                        } else {
                          that.showDialog({
                            title: resDatasno.message,
                            icon: 'fail',
                            tip: ['']
                          })
                        }
                        setTimeout(() => {
                          wx.navigateBack({
                            delta: 1,
                          })
                        }, 2000)
                      }
                    })
                  })
                } else {
                  wx.getSystemInfo({
                    success(resd) {
                      console.log(resd, '设备');
                      locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
                      locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
                      bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
                      if (!locationEnabled) {
                        that.showDialog({
                          title: '手机未打开定位功能',
                          icon: 'fail',
                          tip: ['']
                        })
                      } else if (!locationAuthorized) {
                        that.showDialog({
                          title: '微信未授权定位权限',
                          icon: 'fail',
                          tip: ['请前往设置-应用内打开', '微信定位信息权限']
                        })
                      } else if (!bluetoothEnabled) {
                        that.showDialog({
                          title: '手机蓝牙未打开',
                          icon: 'fail',
                          tip: ['请前往设置-应用内打开', '手机蓝牙']
                        })
                      } else {
                        wx.getSetting({
                          success: restt => {
                            console.log(restt);
                            let authSetting = restt.authSetting
                            if (authSetting['scope.userLocation']) {
                              if (authSetting['scope.bluetooth']) {
                                // 开始搜索蓝牙设备
                                if (that.data.modelid == 'iPhone') {
                                  that.startBluetoothDeviceDiscovery()
                                } else {
                                  wx.openBluetoothAdapter({
                                    success: blueres => {
                                      wx.getBluetoothAdapterState({
                                        //蓝牙的匹配状态
                                        success: (res1) => {
                                          console.log(res1, "本机设备的蓝牙已打开");
                                          if (!res1.available) {
                                            that.showDialog({
                                              title: '手机蓝牙获取失败',
                                              icon: 'fail',
                                              tip: ['请前往设置-应用内打开', '手机蓝牙']
                                            })
                                            return
                                          }
                                          //生成密钥存储
                                          let keys;
                                          keys = wx.getStorageSync('chb_key').split(':')
                                          wx.setStorageSync('key_K', that.keysfun(keys))
                                          that.setData({
                                            deviceId: wx.getStorageSync('chb_key')
                                          })
                                          wx.setStorageSync('deviceId', wx.getStorageSync('chb_key'))
                                          that.createBLEConnection(wx.getStorageSync('chb_key'))
                                        },
                                        fail(error) {
                                          that.showDialog({
                                            title: '手机蓝牙未打开',
                                            icon: 'fail',
                                            tip: ['请前往设置-应用内打开', '手机蓝牙']
                                          })
                                        },
                                      });
                                    },
                                    fail() {
                                      that.showDialogsq({
                                        title: '请授权蓝牙权限',
                                        icon: 'warning',
                                        tip: ['']
                                      })
                                    }
                                  })
                                }

                              } else {
                                that.showDialogsq({
                                  title: '请授权蓝牙权限',
                                  icon: 'warning',
                                  tip: ['']
                                })
                              }
                            } else {
                              that.showDialogsq({
                                title: '请给予微信定位权限',
                                icon: 'warning',
                                tip: ['']
                              })
                            }
                          }
                        })
                      }
                    },
                    fail() {
                      that.showDialog({
                        title: '手机未打开定位功能',
                        icon: 'fail',
                        tip: ['']
                      })
                    }
                  })
                }
              } else if (resdeviceNo.data.code == 5016) {
                that.showDialog({
                  title: '该设备已出租',
                  icon: 'fail',
                  tip: ['请将设备归还后在进行配置']
                })
                wx.closeBluetoothAdapter()
              } else if (resdeviceNo.data.code == 5012) {
                that.showDialog({
                  title: '该设备已损坏',
                  icon: 'fail',
                  tip: ['请联系厂家维修设备']
                })
                wx.closeBluetoothAdapter()
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 2000)
              } else if (resdeviceNo.data.code == 5015) {
                that.showDialog({
                  title: '非本科室设备',
                  icon: 'fail',
                  tip: ['非本科室设备无法', '进行任何操作']
                })
                wx.closeBluetoothAdapter()
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 2000)
              } else if (resdeviceNo.data.code == 5013) {
                that.showDialog({
                  title: resdeviceNo.data.message,
                  icon: 'fail',
                  tip: ['']
                })
                wx.closeBluetoothAdapter()
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 2000)
              } else {
                if (resdeviceNo.data.message.indexOf(',')) {
                  let arr = resdeviceNo.data.message.split(',')
                  let arr1 = []
                  arr.map((item, index) => {
                    if (index != 0) {
                      arr1.push(item)
                    }
                  })
                  that.showDialog({
                    title: arr[0],
                    icon: 'fail',
                    tip: [arr1]
                  })
                  wx.closeBluetoothAdapter()
                } else {
                  that.showDialog({
                    title: resdeviceNo.data.message,
                    icon: 'fail',
                    tip: ['']
                  })
                  wx.closeBluetoothAdapter()
                }
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 2000)
              }
            })
          })

        } else {
          that.setData({
            btnFis: false
          })
          app.showMsg('无效二维码!')
        }
      },
      fail(err) {
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  showDialog({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  showDialogt({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogt').show()
  },

  showDialogsq({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  shouquan() {
    wx.openSetting()
  },
  colsFun() {
    this.getSlist()
  },
  /**
   * 用户点击设备归还
   */
  bindtapEquipmentReturn() {
    // console.log(this.hex10StrTime('00000000020002000200020004000900').sumTime); //总使用时长
    // console.log(this.hex10StrTime('00000000020002000200020004000900').sumTimeStrArr);
    let that = this
    let locationEnabled = false
    let locationAuthorized = false
    let bluetoothEnabled = false
    wx.getSystemInfo({
      success(resd) {
        console.log(resd, '设备');
        locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
        locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
        bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
        if (!locationEnabled) {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
        } else if (!locationAuthorized) {
          that.showDialog({
            title: '微信未授权定位权限',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '微信定位信息权限']
          })
        } else if (!bluetoothEnabled) {
          that.showDialog({
            title: '手机蓝牙未打开',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '手机蓝牙']
          })
        } else {
          wx.getSetting({
            success: res => {
              console.log(res);
              let authSetting = res.authSetting
              if (authSetting['scope.userLocation']) {
                if (authSetting['scope.bluetooth']) {
                  wx.showLoading({
                    title: '归还中...',
                    mask: true
                  })
                  that.BleWrite(encryptionData(that.data.commandEnd, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                } else {
                  that.showDialogsq({
                    title: '请授权蓝牙权限',
                    icon: 'warning',
                    tip: ['']
                  })
                  // wx.openBluetoothAdapter({
                  //   success: blueres => {
                  //     wx.showLoading({
                  //       title: '归还中...',
                  //       mask: true
                  //     })
                  //     that.BleWrite(encryptionData(that.data.commandEnd, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                  //   },
                  //   fail() {
                  //     that.showDialogsq({
                  //       title: '请授权蓝牙权限',
                  //       icon: 'warning',
                  //       tip: ['']
                  //     })
                  //   }
                  // })
                }
              } else {
                that.showDialogsq({
                  title: '请给予微信定位权限',
                  icon: 'warning',
                  tip: ['']
                })
              }
            }
          })
        }
      },
      fail() {
        that.showDialog({
          title: '手机未打开定位功能',
          icon: 'fail',
          tip: ['']
        })
      }
    })
  },
  onShow() {
    this.setData({
      modelid: wx.getStorageSync('modelid')
    })

    // wx.closeBluetoothAdapter({
    //   success(res) {},
    //   fail(res) {}
    // })
  },
  /**
   * 用户点击强制归还
   */
  bindtapImperative() {
    this.selectComponent('#dialogImperative').show()
  },
  /**
   * 用户点击确定
   */
  bindtapConfirm() {
    this.selectComponent('#dialogImperative').hide()
    this.selectComponent('#imperativeReturn').show()
  },
  /**
   * 用户点击取消
   */
  bindtapCancel() {
    this.selectComponent('#dialogImperative').hide()
  },
  /**
   *  用户点击确定更换
   */
  bindtapReplacement() {
    this.selectComponent('#dialogReplacement').show()
  },
  createBLEConnection(deviceId) {
    let that = this
    wx.showLoading({
      title: '设备搜索中',
      mask: true
    })
    let trimA = setTimeout(() => {
      if (wx.getStorageSync('timeiS')) {
        if (wx.getStorageSync('timeiS') >= 2) {
          that.showDialog({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请前往设置-应用内打开手机蓝牙', '请勿下拉打开蓝牙！']
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000)
        } else {
          wx.setStorageSync('timeiS', Number(wx.getStorageSync('timeiS')) + 1)
          that.showDialogt({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
          })
        }
      } else {
        wx.setStorageSync('timeiS', 1)
        that.showDialogt({
          title: '蓝牙未响应',
          icon: 'fail',
          tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
        })
      }
      that.setData({
        btnFis: false
      })
      wx.closeBLEConnection()
      wx.closeBluetoothAdapter()
      clearTimeout(trimA)
      trimA = null
      wx.hideLoading()
    }, 5000)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success(rest) {
        wx.hideLoading()
        wx.removeStorageSync('timeiS')
        clearTimeout(trimA)
        trimA = null
        setTimeout(() => {
          that.getBLEDeviceServices(deviceId);
        }, 1000)
        wx.stopBluetoothDevicesDiscovery({
          success(res) {}
        });
      },
      fail(err) {
        // if(trimA){
        //   that.showDialog({
        //     title: '蓝牙访问失败',
        //     icon: 'fail',
        //     tip: ['请重新扫码']
        //   })
        // }

        wx.closeBLEConnection()
        wx.closeBluetoothAdapter()
        // clearTimeout(trimA)
        // trimA = null
        // wx.hideLoading()
        that.setData({
          btnFis: false
        })

      }
    });
  },
  //设备指令 蓝牙数据
  startBluetoothDeviceDiscovery() {
    let that = this;
    wx.openBluetoothAdapter({
      success: blueres => {
        wx.getBluetoothAdapterState({
          //蓝牙的匹配状态
          success: (res1) => {
            console.log(res1, "本机设备的蓝牙已打开");
            if (!res1.available) {
              that.showDialog({
                title: '手机蓝牙获取失败',
                icon: 'fail',
                tip: ['请前往设置-应用内打开', '手机蓝牙']
              })
              return
            }
            wx.startBluetoothDevicesDiscovery({
              refreshCache: false,
              success: (res) => {
                // // 发现外围设备
                wx.showLoading({
                  title: '设备搜索中',
                  mask: true
                })
                that.getDeviceId().then(response => {
                  console.log(response, '查看返回值');
                  if (response == undefined) {
                    that.showDialogt({
                      title: '设备蓝牙未打开',
                      icon: 'fail',
                      tip: ['请检查设备蓝牙是否打开；', '设备电量是否充足。']
                    })
                    wx.closeBluetoothAdapter()
                    return
                  }
                  //生成密钥存储
                  let keys;
                  keys = response.newdeviceId.split(':')
                  wx.setStorageSync('key_K', that.keysfun(keys))
                  that.setData({
                    deviceId: response.deviceId
                  })
                  wx.setStorageSync('deviceId', response.deviceId)
                  if (response.deviceId) {
                    wx.createBLEConnection({
                      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                      deviceId: response.deviceId,
                      success(rest) {
                        wx.stopBluetoothDevicesDiscovery({
                          success(res) {
                            wx.hideLoading()
                            that.getBLEDeviceServices(response.deviceId)
                          }
                        });
                      },
                      fail(err) {
                        console.log(err);
                      }
                    });
                  }
                })
              }
            })
          },
          fail(error) {
            that.showDialog({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
          },
        });
      },
      fail() {
        that.showDialogsq({
          title: '请授权蓝牙权限',
          icon: 'warning',
          tip: ['']
        })
      }
    })
  },
  //密钥生成
  keysfun(data) {
    let that = this
    let strs = '545a5a59' + data.join('')
    data.map((item, index) => {
      let F = parseInt(('0x' + item)) + parseInt(('0x0' + (index + 1)))
      strs += F.toString(16)
    })
    return strs
  },
  getBLEDeviceServices(deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success: (res) => {
        console.log(res, '连接成功返回值');
        wx.onBLEConnectionStateChange(function (res) {
          // 该方法回调中可以用于处理连接意外断开等异常情况
          if (!res.connected) {
            that.showDialog({
              title: '蓝牙已断开',
              icon: 'fail',
              tip: ['请重新扫码连接']
            })
            wx.offBLEConnectionStateChange()
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 2000)
          }
        })
        if (res.services) {
          let resA = res.services
          res.services.map((item, index) => {
            if (item.isPrimary) {
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: item.uuid,
                success: (resServe) => {
                  console.log(resServe, '蓝牙服务');
                  resServe.characteristics.map(vtm => {
                    if (vtm.uuid == '0000FFF6-0000-1000-8000-00805F9B34FB') {
                      that.setData({
                        UUID1: resA[index].uuid,
                        UUID2: vtm.uuid
                      })
                      wx.setStorageSync('UUID1',
                        resA[index].uuid)
                      wx.setStorageSync('UUID2',
                        vtm.uuid)
                      that.notifyBLECharacteristicValueChange(
                        deviceId, resA[index].uuid,
                        vtm.uuid, true);
                    }
                  })
                }
              })
              console.log(item.uuid, '设备UUID');
            }
          })

        }
      }
    })
  },
  // 向蓝牙写入数据
  BleWrite(instruction, characteristicIdA, serviceIdA) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let _this = this
    _this.setData({
      types: 1
    })
    let serviceId = serviceIdA;
    let characteristicId = characteristicIdA;
    let deviceId = _this.data.deviceId
    const buffer = _this.hex2ArrayBuffer(instruction);
    console.log('buffer=======================', buffer)
    wx.writeBLECharacteristicValue({
      deviceId, // 蓝牙设备 deviceId
      serviceId, // 蓝牙服务uuid,即第二个uuid
      characteristicId, // 蓝牙特征值的 (即 writeId)
      value: buffer, // 这里的value是ArrayBuffer类型
      success(res) {
        console.log('指令下发成功==', res.errMsg, res)
        console.log('指令下发成功传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.readBLECharacteristicValue({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
          deviceId: deviceId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
          serviceId: serviceId,
          // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
          characteristicId: characteristicId,
          success: (res) => {
            console.log('readBLECharacteristicValue:success', res)
          },
          fail: (res) => {
            console.log('readBLECharacteristicValue:fail', res)
          }
        })
      },
      fail(err) {
        console.log('写入数据失败', err)
        console.log('指令下发失败传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.hideLoading()
        wx.closeBluetoothAdapter()
        wx.offBLEConnectionStateChange()
        _this.showDialog({
          title: '传输失败',
          icon: 'fail',
          tip: ['请检查设备与手机蓝牙是否打开；', '设备电量是否充足。']
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 2000)
      }
    })
  },
  //监听开始和取消
  async notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
    let that = this;
    wx.notifyBLECharacteristicValueChange({
      state: state, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        that.BleWrite(encryptionData(that.data.commandStart, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
        // that.BleWrite(encryptionData(that.data.commandEnd, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
        wx.showLoading({
          title: '查询中...',
          mask: true
        })
        console.log(res, '监听的值看看');
        if (!state) {
          that.notifyBLECharacteristicValueChange(that.data.deviceId, that.data.serviceId, that.data
            .characteristicId, true);
        }
        wx.onBLECharacteristicValueChange(
          function (resa) {
            if (that.data.types == 1) {
              let a = that.buf2hex(resa.value)
              console.log(decryptData(a, wx.getStorageSync('key_K')));
              let successAC = decryptData(a, wx.getStorageSync('key_K')).substr(0, 8)
              console.log(successAC, '成功截取');
              if (successAC == 'bb130100') {
                that.setData({
                  successAB: decryptData(a, wx.getStorageSync('key_K')).substr(8, 20)
                })
              }
              if (successAC == 'b2130000') {
                let newab = that.data.successAB + decryptData(a, wx.getStorageSync('key_K')).substr(8, 12)
                that.setData({
                  sumTimeDays: that.hex10StrTime(newab).sumTime,
                  sumTimeArray: that.hex10StrTime(newab).sumTimeStrArr,
                })
                wx.request({
                  url: app.globalData.serverUrl + '/ddOrder/detail/by/' + that.data.deviceNo,
                  method: 'GET',
                  header: {
                    'token': wx.getStorageSync('token')
                  },
                  success: (ressno => {
                    let resDatasno = ressno.data
                    if (resDatasno.code == 200) {
                      resDatasno.data.order.configurationTime = parseTime(resDatasno.data.order.configurationTime, '{y}-{m}-{d} {h}:{i}:{s}')
                      that.setData({
                        orderData: resDatasno.data.order,
                        orderId: resDatasno.data.order.orderId
                      })
                      wx.hideLoading()
                    } else if (resDatasno.code == 5017) {
                      wx.hideLoading()
                      if (resDatasno.message.indexOf(',')) {
                        let arr = resDatasno.message.split(',')
                        let arr1 = []
                        arr.map((item, index) => {
                          if (index != 0) {
                            arr1.push(item)
                          }
                        })
                        that.showDialog({
                          title: arr[0],
                          icon: 'fail',
                          tip: [arr1]
                        })
                        wx.closeBluetoothAdapter()
                      } else {
                        that.showDialog({
                          title: resDatasno.message,
                          icon: 'fail',
                          tip: ['']
                        })
                      }
                      wx.closeBluetoothAdapter()
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 2000)
                    } else {
                      wx.hideLoading()
                      if (resDatasno.message.indexOf(',')) {
                        let arr = resDatasno.message.split(',')
                        let arr1 = []
                        arr.map((item, index) => {
                          if (index != 0) {
                            arr1.push(item)
                          }
                        })
                        that.showDialog({
                          title: arr[0],
                          icon: 'fail',
                          tip: [arr1]
                        })
                        wx.closeBluetoothAdapter()
                      } else {
                        that.showDialog({
                          title: resDatasno.message,
                          icon: 'fail',
                          tip: ['']
                        })
                      }
                      wx.closeBluetoothAdapter()
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 2000)
                    }
                    console.log(that.data.sumTimeDays, '----', that.data.sumTimeArray);
                  })
                })

              }
              if (successAC == 'aa1401bf') {
                wx.request({
                  url: app.globalData.serverUrl + '/device/return',
                  method: 'POST',
                  header: {
                    'token': wx.getStorageSync('token')
                  },
                  data: {
                    orderId: that.data.orderId
                  },
                  success: (resEnd => {
                    if (resEnd.data.code == 200) {
                      wx.hideLoading()
                      wx.offBLEConnectionStateChange()
                      that.showDialog({
                        title: '归还成功!',
                        icon: 'success',
                        tip: ['该订单已结束']
                      })
                      wx.removeStorageSync('deviceId')
                      wx.removeStorageSync('UUID1')
                      wx.removeStorageSync('UUID2')
                      wx.removeStorageSync('key_K')
                      wx.removeStorageSync('chb_key')
                      if (wx.getStorageSync('deviceId')) {
                        wx.closeBLEConnection({
                          deviceId: wx.getStorageSync('deviceId'),
                          success(res) {},
                          fail(res) {}
                        })
                      }
                      wx.closeBluetoothAdapter()
                      setTimeout(() => {
                        wx.reLaunch({
                          url: '/pages/workbench/workbench',
                        })
                      }, 2000)

                    } else {
                      wx.removeStorageSync('deviceId')
                      if (wx.getStorageSync('deviceId')) {
                        wx.closeBLEConnection({
                          deviceId: wx.getStorageSync('deviceId'),
                          success(res) {},
                          fail(res) {}
                        })
                      }
                      wx.closeBluetoothAdapter()
                      wx.hideLoading()
                      that.showDialog({
                        title: '设备已归还!',
                        icon: 'fail',
                        tip: ['不可重复操作']
                      })
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 2000)
                    }

                  })
                })

              }

            }
          }
        );
      },
      fail(err) {
        wx.removeStorageSync('deviceId')
        wx.removeStorageSync('UUID1')
        wx.removeStorageSync('UUID2')
        wx.removeStorageSync('key_K')
        wx.removeStorageSync('chb_key')
        if (wx.getStorageSync('deviceId')) {
          wx.closeBLEConnection({
            deviceId: wx.getStorageSync('deviceId'),
            success(res) {},
            fail(res) {}
          })
        }
        wx.closeBluetoothAdapter()
        that.showDialog({
          title: '传输失败',
          icon: 'fail',
          tip: ['请检查设备与手机蓝牙是否打开；', '设备电量是否充足。']
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 2000)
      }
    });

  },
  // 发现外围设备
  getDeviceId() {
    let that = this;
    console.log("执行到这--发现外围设备1")
    return new Promise(function (resolve, reject) {
      let deviceId;
      let timer = setTimeout(() => {
        if (!deviceId) {
          wx.hideLoading()
          console.log('清理蓝牙监听')
          that.showDialog({
            title: '设备蓝牙未打开',
            icon: 'fail',
            tip: ['']
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000)
          wx.closeBluetoothAdapter()
          resolve(undefined);
          clearTimeout(timer);
          timer = null
        }
      }, 5000);
      wx.onBluetoothDeviceFound(function (devices) {
        console.log('发现的设备2', devices.devices[0], '-----------', that.data.BTLTEST)
        // if(wx.getStorageSync('modelid')!='当前设备是其他类型'){
        // let newdeviceId = that.addObjretIphone(devices.devices[0].name.slice((devices.devices[0].name.indexOf(' ')+1),(devices.devices[0].name.indexOf(' ')+13)))
        let newdeviceId = that.addObjretIphone(devices.devices[0].name.slice(devices.devices[0].name.indexOf(' ') + 1))
        if (newdeviceId === that.data.BTLTEST) {
          deviceId = devices.devices[0].deviceId;
          let a;
          a = {
            deviceId: devices.devices[0].deviceId,
            newdeviceId: newdeviceId
          }
          resolve(a);
          clearTimeout(timer);
          timer = null
        }
        // }else{
        //   if (devices.devices[0].deviceId == that.data.BTLTEST) {
        //     let myTimer = setInterval(() => {
        //       deviceId = devices.devices[0].deviceId;
        //       let a;
        //       a = {
        //         deviceId: deviceId,
        //       }
        //       resolve(a);
        //       clearInterval(timer);
        //       clearInterval(myTimer);
        //       return;
        //     }, 1000);
        //   }
        // }
      });
    });
  },
  //处理使用时间保留
  hex10StrTime(hex_str) {
    let sumTime = 0
    let sumTimeStr = ''
    let sumTimeStrArr = []
    hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      sumTimeStr += parseInt(h, 16).toString()
      sumTime += parseInt(h, 16)
    })
    console.log(sumTime, '最终结果', sumTimeStr);
    sumTimeStrArr = this.hexEnd10Time(sumTimeStr)
    return {
      sumTime,
      sumTimeStrArr
    }
  },
  hexEnd10Time(hex_str) {
    let sumArr = []
    hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      sumArr.push(Number(h[0]) + Number(h[1]))
    })
    return sumArr
  },
  // 16进制字符串转ArrayBuffer
  hex2ArrayBuffer(hex_str) {
    // let hex_str = 'AA5504B10000B5'
    let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    let buffer = typedArray.buffer
    return buffer
  },
  // ArrayBuffer转16进度字符串
  buf2hex(arrayBuffer) {
    return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2))
      .join('');
  },
  //处理字符
  addObjretIphone(data) {
    let result = "";
    let newarr = []
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    newarr = result.split(':')
    return newarr.reverse().join(':')
  },
  addObjret(data) {
    let result = "";
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    return result
  },
})